package com.jn.mvp.presenter;

import android.content.Context;

import com.jn.mvp.contract.NewsContract;
import com.jn.mvp.entity.News;
import com.jn.mvp.service.NewsService;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class NewsPresenter implements NewsContract.INewsPresenter {

    private NewsContract.INewsView mNewsView;
    private Context mContext;

    public NewsPresenter(NewsContract.INewsView mNewsView, Context mContext) {
        this.mNewsView = mNewsView;
        this.mContext = mContext;
    }

    @Override
    public void getData() {
        String url = "https://api.zxki.cn/";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
        NewsService service = retrofit.create(NewsService.class);
        service.getData()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<News>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull News news) {
                        mNewsView.showData(news);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mNewsView.onHttpFail(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
